<template>
  <div class="permission-content" ref="permisssTab">
    <div class="userName">
      <span class="user-l">当前{{ query.orgId ? "组织：" : "用户：" }}</span
      >{{ query.orgId ? showName || query.name : query.userName }}
    </div>
    <a-tabs v-model:activeKey="tabActive" @change="changeTopTabs">
      <a-tab-pane key="1" tab="站群权限">
        <div class="add-site-tip-top scrollBar">
        <div v-if="Number(query.allPermissions) === 0 || query.allPermissions === undefined" class="left-splace">
          <!-- <a-button @click="checkAll">{{buttonText}}</a-button> -->
          <a-checkbox v-if="siteTree.length" v-model:checked="checkedValue" @change="checkAll">全选</a-checkbox>
        </div>
          <base-tree
            :treeData="siteTree"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkSiteKeys"
            :fieldNames="fieldNames"
            @checked_Keys="checked_Keys"
            :selectable="false"
            :defaultExpandAll="true"
            :height="600"
          >
            <template #slotProps="{ id }">
              <a-tooltip placement="right" v-if="id == -1">
                <template #title>
                  <span>选中后，用户可拥有后续新增的站群权限</span>
                </template>
                <i
                  class="iconfont icon-hint1"
                  style="font-size: 16px; margin-left: 8px; color: rgba(0, 0, 0, 0.45)"
                >
                </i>
              </a-tooltip>
            </template>
          </base-tree>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="菜单/按钮权限">
        <div class="add-site scrollBar">
          <base-tree
            :treeData="menusTree"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkMenuKeys"
            :fieldNames="fieldNames"
            @checked_Keys="checked_Keys"
            class="inlineTree"
            :selectable="false"
            :defaultExpandAll="false"
            
          >
          <!-- :height="688" -->
            <template #slotProps="{ id }">
              <a-tooltip placement="right" v-if="id == -1">
                <template #title>
                  <span>选中后，用户可拥有后续新增的菜单/按钮权限</span>
                </template>
                <i
                  class="iconfont icon-hint1"
                  style="font-size: 16px; margin-left: 8px; color: rgba(0, 0, 0, 0.45)"
                >
                </i>
              </a-tooltip>
            </template>
          </base-tree>
        </div>
      </a-tab-pane>

      <a-tab-pane key="3" tab="站点权限">
        <div class="site-tab">
          <!-- 站点权限表格展示部分 -->
          <virtualTable
            :columns="columns.sitePressionColumns"
            :dataSource="siteTreeTable"
            v-if="tabActive == 3"
            ref="siteTable"
            :isAssignable="isAssignable"
            :height="'550px'"
            :isColumn="false"
          >
          </virtualTable>
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="栏目操作权限">
        <div class="section-tab">
          <a-select
            v-model:value="sectionValue"
            placeholder="请选择站点"
            :options="sectionOptions.map((item: any) => ({ value: item.id, label: item.siteName }))"
            @change="handleChange"
          >
          </a-select>
          <span class="tips">
            操作说明
            <a-tooltip placement="right">
              <template #title>
                <span>请先设置站群权限再设置栏目权限</span>
              </template>
              <span class="iconfont icon-hint1"></span>
            </a-tooltip>
          </span>
          <!-- 栏目权限表格展示部分 -->
          <virtualTable
            :columns="columns.sectionColumns"
            :dataSource="channelTreeTable"
            v-if="tabActive == 4"
            ref="siteTable"
            :isAssignable="isAssignable"
            :isColumn="true"
          >
          </virtualTable>
        </div>
      </a-tab-pane>
      <a-tab-pane key="5" tab="文档权限" v-if="0">
        <div class="document-tab">
          <a-select
            v-model:value="documentValue"
            placeholder="请选择站点"
            :options="documentOptions.map((item: any) => ({ value: item.id, label: item.siteName }))"
            @change="handleChange"
          >
          </a-select>
          <span class="tips">
            操作说明
            <a-tooltip placement="right">
              <template #title>
                <span>请先设置站群权限再设置文档权限</span>
              </template>
              <span class="iconfont icon-hint1"></span>
            </a-tooltip>
          </span>
          <!-- 文档权限表格展示部分 -->
          <!-- <permission-table :columns="columns.documentColumns" :dataSource="docTreeTable" :rowSelection="1"
            :isSelect="true" ref="siteTable" v-if="tabActive == 50" :scroll="{ x: 2090, y: 600 }"> 
          </permission-table>-->
          <virtualTable
            :columns="columns.documentColumns"
            ref="siteTable"
            :dataSource="docTreeTable"
            v-if="tabActive == 5"
            :isAssignable="isAssignable"
          >
          </virtualTable>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from "vue";
import baseTree from "@/components/tree/baseTree.vue";
import columns from "@/components/table/tableConfig/columnsName";
import permissionTable from "@/components/table/permissionTable.vue";
import virtualTable from "@/components/table/virtualTablePerssion.vue";
import request from "@/api/index";
import { useRoute } from "vue-router";
import getters from "@/store/getters";
// type
interface dataSourceType {
  [propName: string]: any;
}
//props
const props = defineProps({
  selectedOrgKeys: {
    type: [Number, String],
  },
  orgName: {
    type: [String, Number],
  },
});
//emit
const emit = defineEmits(["assignable"]);
// data
const { query } = useRoute();
const userInfo = getters.userInfo();
const permisssTab = ref();
const checkStrictly = ref<Boolean>(true); //树型节点选择不关联
//权限tab切换
const fieldNames = reactive({ title: "name", key: "id", disableCheckbox: "assignable" });
const showName = ref<any>(null);
const tabActive = ref<any>("1");
// 左边组织key
const selectedOrgKeys = ref<(string | number | any)[]>([]);
// 路由传来的userId
const querUserId = ref<string | number | any>("");
//站群数据
let siteTree = ref<dataSourceType[]>([]);
const checkSiteKeys = ref<(string | number | any)[]>([]);
//菜单数据
let menusTree = ref<dataSourceType[]>([]);
const checkMenuKeys = ref<(string | number | any)[]>([]);

//站点数据
const isAssignable = ref<Boolean>(true);
let siteTreeTable = ref<dataSourceType[]>([]);
const siteTable = ref();
const siteIds = ref<any[]>([]);
const siteCheckList = ref<any[]>([]);
const buttonText = ref<string>('全选');
const checkedValue = ref<boolean>(true)

//栏目权限
const sectionOptions = ref<dataSourceType[]>([]);
const sectionValue = ref<string | undefined>(undefined);
const channelTreeTable = ref<dataSourceType[]>([]);

//文档权限
const documentOptions = ref<dataSourceType[]>([]);
const documentValue = ref<string | undefined>(undefined);
const docTreeTable = ref<dataSourceType[]>([]);
//watch

watch(
  () => props.selectedOrgKeys,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      selectedOrgKeys.value = [];
      sectionValue.value = "";
      documentValue.value = "";
      selectedOrgKeys.value.push(newVal);
      showName.value = props.orgName;
      getTreeData();
    }
  }
);
watch(() => checkSiteKeys.value, (newVal: any) => {
  // console.log(newVal.length, siteCheckList.value.length);
  if(newVal.length !== siteCheckList.value.length) {
    checkedValue.value = false
  }else {
    checkedValue.value = true
  }
})
//methods
// 选取站群
const checked_Keys = async (obj: dataSourceType) => {
  let isChecked = obj.e.checked;
  tabActive.value == "1" ? (checkSiteKeys.value = obj.checkedKeys.checked) : "";
  console.log(obj.checkedKeys.checked,'obj.checkedKeys.checked');
  
  tabActive.value == "2" ? (checkMenuKeys.value = obj.checkedKeys.checked) : "";
  checkMenuKeys.value = [...new Set(checkMenuKeys.value)];
  if (tabActive.value == "2") {
    //做父子级判断
    nextTick(async () => {
      const loop = (data: dataSourceType) => {
        data.forEach((item: dataSourceType) => {
          if (!isChecked) {
            if (checkMenuKeys.value.includes(item.id)) {
              for (let i = 0; i < checkMenuKeys.value.length; i++) {
                item.id == checkMenuKeys.value[i] ? checkMenuKeys.value.splice(i, 1) : "";
              }
            }
          } else {
            !checkMenuKeys.value.includes(item.id)
              ? checkMenuKeys.value.push(item.id)
              : "";
          }
          if (item.children instanceof Array && item.children.length) {
            loop(item.children);
          }
        });
      };
      await loop(obj.e.node.children || []);
      nextTick(() => {
        loopParent(menusTree.value, obj.e.node.parentId, isChecked, checkMenuKeys.value);
      });
    });
  }
};
// 全选
const checkAll = () => {
  if(checkedValue.value) {
    checkSiteKeys.value = siteCheckList.value
  }else {
    checkSiteKeys.value = []
  }

};
const deepIds = (data: any = []) => {
  if(data) {
    data.forEach((item: any) => {
    if(item.id) {
      siteCheckList.value.push(item.id)
      if(item.children && item.children.length) {
        deepIds(item.children)
      }
    }
  })
  }
};
//改变权限内容tab切换
const changeTopTabs = (activeKey: number) => {
  tabActive.value = activeKey;
  sectionValue.value = "";
  documentValue.value = "";
  getTreeData();
};

// 获取权限树数据、表格权限树数据
const getTreeData = async () => {
  // 获取表格数据
  if (+tabActive.value <= 2) {
    getSitesAndMenu(); //权限树数据
  } else {
    if (+tabActive.value > 3) {
      await getSiteRdecord(); //获取站点下拉选择列表
    }
    getSiteAndChannelAndDoc();
  }
};

// 获取站群|菜单树数据
const getSitesAndMenu = async () => {
  const postData: {} = {
    dataType: tabActive.value,
    orgId: selectedOrgKeys.value[0] || undefined,
    userId: querUserId.value || undefined,
    allPermissions:
      query.allPermissions === undefined
        ? undefined
        : query.allPermissions == "1"
        ? true
        : false,
  };
  const data = (await request.fetchStationGroupMenu(postData)) || {};
  siteIds.value = data.stationVo;
  siteCheckList.value = []
  deepIds(siteIds.value)
  let assignable = data.assignable;
  const loop = (data: dataSourceType[]) => {
    data.forEach((item: dataSourceType) => {
      // 如果assignable为false，意味着都不可编辑

      item.disableCheckbox = !assignable ? !assignable : !item.assignable;
      let length = data.length;
      if (!item.children) {
        for (let i in data) {
          if (data[i].children) {
            length = 0;
          }
        }
        if (length >= 1) {
          item.class = "needInline";
        }
      }
      item.selected = item.hasPerm;
      if (item.hasPerm) {
        tabActive.value == "1" ? checkSiteKeys.value.push(item.id) : "";
        tabActive.value == "2" ? checkMenuKeys.value.push(item.id) : "";
      }
      if (item.children) {
        loop(item.children);
      }
    });
  };
  tabActive.value == "1" ? (checkSiteKeys.value = []) && loop(data.stationVo || []) : "";
  tabActive.value == "2" ? (checkMenuKeys.value = []) && loop(data.menusVo || []) : "";
  siteTree.value = data.stationVo ? data.stationVo : siteTree.value;
  menusTree.value = data.menusVo ? data.menusVo : menusTree.value;
  nextTick(() => {
    assignable =
      tabActive.value == 1
        ? assignable && siteTree.value.length
        : tabActive.value == 2
        ? assignable && menusTree.value.length
        : "";
    emit("assignable", assignable);
  });
};
// 获取 站点|栏目|文档-权限树
const getSiteAndChannelAndDoc = async () => {
  // siteTreeTable
  const postData: dataSourceType = {
    dataType: +tabActive.value,
    orgId: selectedOrgKeys.value[0] || undefined,
    userId: querUserId.value || undefined,
    siteId:
      tabActive.value == 4
        ? sectionValue.value || undefined
        : documentValue.value || undefined,
    allPermissions:
      query.allPermissions === undefined
        ? undefined
        : query.allPermissions == "1"
        ? true
        : false,
  };
  if (!postData.siteId && (tabActive.value == 4 || tabActive.value == 5)) {
    emit("assignable", false);
    channelTreeTable.value = [];
    docTreeTable.value = [];
    return;
  }
  const data = await request.fetchSiteChannelDocumentPerm(postData);
  let assignable = data.assignable;

  isAssignable.value = data.assignable;
  siteTreeTable.value = data.sitePerms || [];
  channelTreeTable.value = data.channelPerms || [];
  docTreeTable.value = data.documentPerms || [];
  assignable =
    tabActive.value == 3
      ? assignable && siteTreeTable.value.length
      : tabActive.value == 4
      ? assignable && channelTreeTable.value.length
      : tabActive.value == 5
      ? assignable && docTreeTable.value.length
      : "";
  emit("assignable", assignable);
};
const getSiteRdecord = async () => {
  //获取站点下拉选择，  因为实时变动，所以每次都得调接口
  const data: {} = {
    orgId: selectedOrgKeys.value[0],
    userId: !query.orgId ? querUserId.value : "",
    allPermissions:
      query.allPermissions === undefined
        ? undefined
        : query.allPermissions == "1"
        ? true
        : false,
  };
  const telData = await request.fetchSiteManageUnpersSiteRecord(data);
  sectionOptions.value = [];
  documentOptions.value = [];
  if (telData.length) {
    sectionOptions.value = telData;
    documentOptions.value = telData;
    sectionValue.value = sectionValue.value ? sectionValue.value : telData[0].id;
    documentValue.value = documentValue.value ? documentValue.value : telData[0].id;
    //record = loop(JSON.parse(JSON.stringify(siteData.value)), selectSiteData.value);
  } else {
    sectionValue.value = undefined;
    documentValue.value = undefined;
  }
};
const handleChange = (value: string) => {
  // 站点变化
  nextTick(() => {
    getSiteAndChannelAndDoc();
  });
};
const loopParent = (
  data: dataSourceType[],
  Pid: number | string,
  isSelected: Boolean,
  selectedKey: (string | number)[]
) => {
  if (!isSelected) {
    return;
  }
  for (let i in data) {
    if (data[i].id == Pid) {
      !selectedKey.includes(data[i].id) ? selectedKey.push(data[i].id) : "";
      if (data[i].parentId) {
        loopParent(menusTree.value, data[i].parentId, isSelected, selectedKey);
      }
    } else {
      if (data[i].children instanceof Array && data[i].children.length) {
        loopParent(data[i].children, Pid, isSelected, selectedKey);
      }
    }
  }
};
//onmounted
onMounted(() => {
  if (query.orgId) {
    selectedOrgKeys.value = [];
    selectedOrgKeys.value.push(+query.orgId);
  } else if (query.userId) {
    querUserId.value = +query.userId;
  }
  getTreeData();
});
//defineExpose
defineExpose({
  permisssTab,
  tabActive,
  siteTree,
  checkSiteKeys,
  menusTree,
  checkMenuKeys,
  siteTable,
  getTreeData,
  sectionValue,
  documentValue,
});
</script>

<style lang="less" scoped>
.permission-content {
  height: 100%;
  overflow: hidden;

  .add-site {
    display: flex;
    flex-direction: column;
    padding-top: 22px;
    padding-bottom: 8px;
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);

    .add-site-tip {
      margin-top: 4px;
      display: flex;
      flex-direction: row;
    }
  }

  .add-site-tip-top {
    padding-top: 22px;
    .left-splace {
      margin-left: 24px;
    }
  }

  .section-tab {
    padding-top: 24px;

    ::v-deep(.ant-select) {
      width: 200px;
    }
  }

  .document-tab {
    padding-top: 24px;
  }
}
</style>
<style lang="less">
.permission-content {
  .ant-tabs.ant-tabs-top {
    height: 100%;
    overflow: hidden;

    .ant-tabs-content-holder {
      height: 100%;
      overflow: hidden;
      padding-bottom: 24px;

      .ant-tabs-content.ant-tabs-content-top {
        height: 100%;
        overflow: hidden;

        .ant-tabs-tabpane-active {
          height: calc(100%);
          position: relative;
          overflow: hidden;
        }

        .scrollBar {
          height: 100%;
          overflow-y: auto;
        }
      }
    }
  }
}
</style>
<style lang="less">
.inlineTree {
  .ant-tree-list-holder-inner {
    display: block !important;

    .needInline {
      width: 14.28%;
      display: inline-flex;
      min-width: 150px;
    }
  }
}

.document-tab,
.section-tab {
  .ant-select-single {
    min-width: 130px;
  }
}

.userName {
  margin-bottom: 7px;
  font-size: 15px;
  color: black;

  .user-l {
    color: #7f7f7f;
  }
}

.tips {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}
</style>
